package com.vincent.jvmtest.common;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author vincent
 * @date 2019/3/3
 * @description
 */
public class DelayedVo<T> implements Delayed {
    private long time;
    private T value;

    public DelayedVo(long timeout, T value) {
        this.time = System.currentTimeMillis() + timeout;
        this.value = value;
    }

    public long getTime() {
        return time;
    }

    public T getValue() {
        return value;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert((this.time - System.currentTimeMillis()), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == this) {
            return 0;
        } else if (o instanceof DelayedVo) {
            if (this.getTime() == ((DelayedVo) o).getTime()) {
                return 0;
            } else if (this.getTime() > ((DelayedVo) o).getTime()) {
                return 1;
            } else {
                return -1;
            }
        } else {
            long d = (getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
            return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
        }
    }
}
